package com.infinitus.activity.web;

import com.infinitus.activity.pojo.DTO.WeChatReturnDto;
import com.infinitus.activity.pojo.VO.ResponseVO;
import com.infinitus.activity.util.ApiUtils;
import com.infinitus.activity.util.KeyGenerator;
import com.infinitus.activity.util.MD5Util;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.client.RestTemplate;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Pattern;

/**
 * @author: luzhenjie
 * @create: 2019/3/11
 * @desc:
 */
@Controller
@RequestMapping(value = "/sys")
public class LoginController {

    private static Logger logger = Logger.getLogger(LoginController.class);

    @Value("${ydapi.appId}")
    private String appId;

    @Value("${ydapi.appSecret}")
    private String appSecret;

    @Value("${ydapi.env}")
    private String baseUrl;   //base路径

    @Value("${ydapi.login.path}")
    private String loginPath;  //登录路径

    @Value("${deploycolId}")
    private String deploycolId;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * @Desc 用户登录
     */
    @RequestMapping(value = "/login" , method = RequestMethod.POST)
    public ResponseEntity<?> login(@RequestParam String dealerNo ,@RequestParam String password) {
        /**
         * @Desc 卡号格式合法性校验
         */
        if(!Pattern.matches("^\\d{9}$", dealerNo)) {
            return ResponseEntity.badRequest().body(40001);
        }

        try {
            boolean invoking = ApiUtils.invoking(appId,appSecret,baseUrl,loginPath,dealerNo,password);
            if(invoking) {
                Boolean hasKey = stringRedisTemplate.hasKey(KeyGenerator.getLoginAlready(deploycolId,dealerNo));
                if (!hasKey) {
                    stringRedisTemplate.opsForValue().set(KeyGenerator.getLoginAlready(deploycolId,dealerNo), "0");
                }
                return ResponseEntity.ok().build();
            }else{
                return ResponseEntity.badRequest().body("密码不对");
            }
            /*stringRedisTemplate.opsForValue().set(KeyGenerator.getLoginAlready(deploycolId,dealerNo), "0");
            return ResponseEntity.ok().build();*/
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e);
        }

    }

}